package f.h.dragon.util;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * 主机工具类：提供诸如获取ip、名称等通用操作
 * 
 * @author Wenlong Meng(wenlong.meng@gmail.com)
 * @version 1.0 at 2011/10/27
 * @since 1.0
 */
public class ServerUtil {

	//local variables
	/**
	 * ip
	 */
	private static String ip;

	/**
	 * 获取本机ip，通过静态变量一次获取多次使用来提高效率
	 * 
	 * @return
	 * @throws SocketException
	 */
	public static String getIp() {
		// 根据网卡取本机配置的IP
		if(ip == null || ip.trim().length() < 1){
			NetworkInterface network = null;
			try {
				network = NetworkInterface.getByName("eth0");
				for (InterfaceAddress interfaceAddress : network.getInterfaceAddresses()) {
					InetAddress address = interfaceAddress.getAddress();
					if (!address.getHostAddress().contains(":")) {
						ip = address.getHostAddress();
						break;
					}
				}
			} catch (SocketException e) {
				throw new RuntimeException(e);
			}
		}
		return ip;
	}
	
	/**
	 * testing...
	 * 
	 * @param args
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException{
		// 根据网卡取本机配置的IP
		NetworkInterface network = null;
		try {
			network = NetworkInterface.getByName("eth0");
			for (InterfaceAddress interfaceAddress : network.getInterfaceAddresses()) {
				InetAddress address = interfaceAddress.getAddress();
				if (!address.getHostAddress().contains(":")) {
					System.out.println(address.getHostAddress());
					System.out.println(address.getCanonicalHostName());
					System.out.println(address.getHostAddress());
					System.out.println(address.getHostName());
					System.out.println(InetAddress.getLocalHost());
					break;
				}
			}
		} catch (SocketException e) {
			throw new RuntimeException(e);
		}
	}

}
